iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 5

[Day5] Codewars >>>Take a Number And Sum Its Digits Raised To The Consecutive Powers (Python)

  • 分享至 

  • xImage
  •  

題目(6kyu):

The number 89 is the first integer with more than one digit that fulfills the property >partially introduced in the title of this kata. What's the use of saying "Eureka"? >Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2
The next number in having this property is 135.
See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that >defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the >range that fulfills the property described above.

Let's see some cases (input -> output):
1, 10 -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
1, 100 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

If there are no numbers of this kind in the range [a, b] the function should output an >empty list.
90, 100 --> []

解題思路

題目理解:將數字number從第一個數字開始,依序以1,2,3...來做次方,並將所有值相加後若等於number本身,則將此數收集於list中。設計函數以返還列表包含a~b內所有符合此特性的自然數,若無則返還[]。

def sum_dig_pow(a, b): 
    result = []
    for number in range(a,b+1):
        #先將待檢驗數字number轉換成列表保存
        number_lst = [int(s) for s in str(number)]
        sum_num = 0
        #利用len()的長度與number位數相符合,配合迴圈使次方遞增
        for i in range(len(number_lst)):
            sum_num += number_lst[i]**(i+1)
        if sum_num == number:
            result.append(number) 
    return result

上一篇
[Day4] Codewars >>>The search for Primes! Twin Primes!(Python)
下一篇
[Day6] Codewars >>> Two Sum (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言